package com.crane.app.web.interceptor;


import com.crane.common.core.utils.BaseContextHandler;
import com.crane.common.framework.jwt.JwtUserToken;
import com.crane.common.framework.jwt.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 暂时只考虑token的session。
 *
 * @Author: zhenxing.pi
 * @Date: 2020/7/15 19:35
 */

@Slf4j
@Component
public class AppSessionInterceptor extends HandlerInterceptorAdapter {

    private static final String APP_PREFIX = "/app";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //静态资源处理
        if (handler instanceof ResourceHttpRequestHandler) {
            return super.preHandle(request, response, handler);
        }
        if (request.getServletPath().startsWith(APP_PREFIX)) {
            String userInfoStr = request.getHeader(JwtUserToken.HEADER_USER);
            if (!StringUtils.isEmpty(userInfoStr)) {
                //判断会话是否存在
                log.info("request请求地址path[{}] uri[{} token{}]", request.getServletPath(), request.getRequestURI(), userInfoStr);
                try {
                    JwtUserToken jwtUser = JwtUtil.getInfoFromToken(userInfoStr, JwtUserToken.class).getUserInfo();
                    BaseContextHandler.setUserId(jwtUser.getUserId());
                    BaseContextHandler.setRandomKey(jwtUser.getRandomKey());
                } catch (Exception e) {
                    log.error("getSessionByToken error={}", e.getMessage(), e);
                }
            }
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
